package com.yingxin.yxerp.module.tplus.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yxerp.module.tplus.auth.configuration.TplusAppConfig;
import com.yingxin.yxerp.module.tplus.auth.entity.Auth;
import com.yingxin.yxerp.module.tplus.auth.mapper.AuthMapper;
import com.yingxin.yxerp.module.tplus.auth.service.IAuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

/**
 * tplus-鉴权
 */

@Service
public class AuthServiceImpl extends ServiceImpl<AuthMapper, Auth> implements IAuthService {

     private static final String GET_TOKEN = "https://openapi.chanjet.com/auth/getToken";

     private static final String REFRESH_TOKEN = "https://openapi.chanjet.com/auth/refreshToken";

    @Autowired
    private TplusAppConfig tplusAppConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 临时授权码 换 token
     */
    @Override
    public void tokenRequestByCode(String code) {
        if (StringUtils.isBlank(code)) {
            throw new BizException("授权码为空");
        }
        String url = GET_TOKEN + "?grantType=authorization_code"
                + "&appKey=" + tplusAppConfig.getAppKey()
                + "&redirectUri=" + tplusAppConfig.getRedirectUri()
                + "&code=" + code;
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        if (response.getStatusCodeValue() != 200) {
            throw new BizException("获取token失败");
        }
        saveToken(response);
    }

    /**
     * 刷新 token
     */
    public void refreshToken() {
        Auth auth = getById("1");
        if (auth == null) {
            return;
        }
        String url = REFRESH_TOKEN + "?grantType=refresh_token"
                + "&appKey=" + tplusAppConfig.getAppKey()
                + "&refreshToken=" + auth.getRefreshToken();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        if (response.getStatusCodeValue() != 200) {
            throw new BizException("refreshToken失败");
        }
        saveToken(response);
    }

    /**
     * 保存token
     */
    private void saveToken(ResponseEntity<String> response) {
        JSONObject body = JSONObject.parseObject(response.getBody());
        JSONObject result = body.getJSONObject("result");
        // accessToken
        String accessToken = result.getString("access_token");

        // expiresIn
        long expiresIn = result.getLongValue("expires_in");
        expiresIn = expiresIn * 1000 + System.currentTimeMillis();
        Date tokenExpire = new Date();
        tokenExpire.setTime(expiresIn);

        // refreshToken
        String refreshToken = result.getString("refresh_token");

        // refreshExpiresIn
        long refreshExpiresIn = result.getLongValue("refresh_expires_in");
        refreshExpiresIn = refreshExpiresIn * 1000 + System.currentTimeMillis();
        Date refreshExpire = new Date();
        refreshExpire.setTime(refreshExpiresIn);

        Auth auth = new Auth();
        auth.setId("1");
        auth.setAccessToken(accessToken);
        auth.setExpiresIn(tokenExpire);
        auth.setRefreshToken(refreshToken);
        auth.setRefreshExpiresIn(refreshExpire);
        saveOrUpdate(auth);
    }


    /**
     * 查询 accessToken
     */
    @Override
    public String getAccessToken() {
        Auth auth = getById("1");
        if (auth == null) {
            return null;
        }
        return auth.getAccessToken();
    }

}
